from google.appengine.api import users
from google.appengine.runtime import DeadlineExceededError
from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

### Wrapper Functions ###

def login_required(func):
  """ A function decorator that checks for login credentials """
  def _wrapper(request, *args, **kw):
      user = request.user
      if user:
          return func(request, *args, **kw)
      else:
          return HttpResponseRedirect(users.create_login_url(request.get_full_path()))
  
  return _wrapper

### Other functions ###

def respond(request, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    template: The template name.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  # Add some params to the context dictionary
  params['user'] = request.user
  params['request'] = request
  full_path = request.get_full_path().encode('utf-8')
  if request.user is None:
    params['sign_in'] = users.create_login_url(full_path)
  else:
    params['sign_out'] = users.create_logout_url(full_path)
  
  # Try rendering it, displaying relevent errors
  try:
    return render_to_response(template, params)
  except DeadlineExceededError:
    logging.exception('DeadlineExceededError')
    return HttpResponse('DeadlineExceededError', status=503)
  except CapabilityDisabledError, err:
    logging.exception('CapabilityDisabledError: %s', err)
    return HttpResponse('Rietveld: App Engine is undergoing maintenance.'
                        'Please try again in a while. ' + str(err),
                        status=503)
  except MemoryError:
    logging.exception('MemoryError')
    return HttpResponse('MemoryError', status=503)
  except AssertionError:
    logging.exception('AssertionError')
    return HttpResponse('AssertionError')

# def cadet(request, first_name, last_name):
#   template_values = {
#     'first_name': first_name,
#     'last_name': last_name,
#   }
#   return respond(request, 'badmin/cadet.html', template_values)